import http from './http'
import util from './util'
import store from '../../store/index'
import wx from 'weixin-js-sdk'
import { MessageBox, Toast } from 'mint-ui'
import router from '../../router.js'

let resImgs = []
export default {
  uploadFiles (files, i, callback, hasHost = false) {
    const data = new FormData()
    data.append('icon', files[i])
    http.post('/api/greengage/alumni/editIcon', data, { headers: { loading: true } }).then((res) => {
      if (res.code === 200) {
        if (hasHost) {
          resImgs.push(util.apiHost + res.data)
        } else {
          resImgs.push(res.data)
        }
        if (i < files.length - 1) {
          i++
          this.uploadFiles(files, i, callback, hasHost)
        } else {
          callback(resImgs)
          resImgs = []
        }
      } else {
        Toast(res.msg)
      }
    }).catch((err) => {
      err.msg && Toast(err.msg)
    })
  },
  appLinkTo (url) {
    // console.log('now url:',router.history.current.fullPath);
    if (!util.isReg()) {
      this.noRegAlert()
    } else {
      router.push({ path: url })
    }
  },
  noRegAlert () {
    MessageBox.confirm('此功能仅限注册用户~', '提示', {
      confirmButtonText: '去注册'
    }).then(action => {
      router.push({ path: '/reg' })
    })
  },
  getCityList (callback) {
    const cityList = window.sessionStorage.cityList
    if (cityList === undefined) {
      http
        .get('/api/greengage/user/getCity')
        .then(res => {
          if (res.code === 200) {
            const str = res.data
            window.sessionStorage.cityList = JSON.stringify(str)
            callback(str)
          }
        })
    } else {
      callback(JSON.parse(cityList))
    }
  },
  getCountryList (callback) {
    const countryList = window.sessionStorage.countryList
    if (countryList === undefined) {
      http
        .get('/api/greengage/user/getCountry')
        .then(res => {
          if (res.code === 200) {
            const str = res.data
            window.sessionStorage.countryList = JSON.stringify(str)
            callback(str)
          }
        })
    } else {
      callback(JSON.parse(countryList))
    }
  },
  getBaseUserInfo (callback) {
    const userInfo = store.state.userInfo
    if (userInfo === null) {
      http
        .get('/api/greengage/user/user')
        .then(res => {
          store.state.userInfo = res.data
          callback(res.data)
        })
    } else {
      callback(userInfo)
    }
  },
  getDetailUserInfo (callback) {
    http
      .get('/api/greengage/user/userDetail')
      .then(res => {
        store.state.userDetailInfo = res.data
        callback(res.data)
      })
  },
  // 获取用户名片信息
  getCardDetail (cb) {
    http.post('/api/greengage/user/myCard').then(res => {
      if (res.code === 200) {
        cb(res.data)
      } else {
        Toast(res.msg)
      }
    }).catch(res => {
      if (res.msg) {
        Toast(res.msg)
      }
    })
  },
  // share({ signPath: signPath, path: path, title: title, desc: desc, callback: callback }) {
  share (objParams, callback) {
    // if (util.isiOS()) {
    //   if (window.sessionStorage.url) {
    //     url = window.sessionStorage.url;
    //   } else {
    //     // 可能是分享出来的
    //     alert("没找到url")
    //   }
    // }

    const obj = {
      path: window.location.origin + '/group_avatar/', // 跳转地址
      title: '北京航空航天大学68周年庆云合影邀你来参加～',
      desc: ' ',
      imgUrl: window.location.origin + '/group_avatar/share/logo.jpg',
      invite: ''
    }
    if (objParams && typeof objParams === 'object') {
      for (const p in objParams) {
        obj[p] = objParams[p]
      }
    }
    if (objParams && typeof objParams === 'function') {
      callback = objParams
    }
    // if (!obj.signPath) return;
    // alert("share:" + JSON.stringify(obj))
    const pathArr = store.state.circle.wxConfig
    if (pathArr[obj.signPath]) {
      const data1 = pathArr[obj.signPath]
      wx.config({
        debug: false,
        appId: data1.appId,
        timestamp: data1.timestamp,
        nonceStr: data1.nonceStr,
        signature: data1.signature,
        jsApiList: data1.jsApiList
      })
    } else {
      // http.post('/auth/wechat/wechatConfig', { url: window.location.href }).then(res => {
      //   if (res.code === 200) {
      //     const data = res.data
      //     if (!pathArr[window.location.href]) {
      //       pathArr[window.location.href] = res.data
      //     }
      //     wx.config({
      //       debug: false,
      //       appId: data.appId,
      //       timestamp: data.timestamp,
      //       nonceStr: data.nonceStr,
      //       signature: data.signature,
      //       jsApiList: data.jsApiList
      //     })
      //   }
      // })
      http.get('/auth/wechat/wechatConfig?url=' + window.location.href)
        .then((res) => {
          // debugger;
          if (res.code === 200) {
            const data = res.data
            if (!pathArr[window.location.href]) {
              pathArr[window.location.href] = res.data
            }
            wx.config({
              debug: false,
              appId: data.appId,
              timestamp: data.timestamp,
              nonceStr: data.nonceStr,
              signature: data.signature,
              jsApiList: data.jsApiList
            })
          }
        })
    }

    wx.ready(function () {
      wx.showAllNonBaseMenuItem()

      // wx.onMenuShareQQ(shareData);
      // wx.onMenuShareWeibo(shareData);
      const link2 = window.location.href

      const shareData = {
        title: obj.title,
        desc: obj.desc,
        link: link2,
        imgUrl: obj.imgUrl,
        success: function () {
          // 用户确认分享后执行的回调函数
          // Toast('分享成功');
        },
        cancel: function () {
          // 用户取消分享后执行的回调函数
        },
        complete: function () {
          typeof callback === 'function' && callback()
        },
        fail: function (fail) {
          console.log('share fail', fail)
        }
      }
      wx.onMenuShareAppMessage(shareData)
      wx.onMenuShareTimeline(shareData)
    })
  },
  // 注册成功后保存token
  regSuccessFn (token) {
    if (util.isExits('init')) {
      const temp = JSON.parse(localStorage.init)
      temp.token = token
      temp.audit = 1
      localStorage.init = JSON.stringify(temp)
    }
    http.defaults.headers.common.Authorization = token
  },
  // 注册后进入审核，将audit状态置为0，表示审核中
  regCheckingFn () {
    if (util.isExits('init')) {
      const temp = JSON.parse(localStorage.init)
      temp.audit = 0
      localStorage.init = JSON.stringify(temp)
    }
  },
  getToken (openid, callback) {
    http.get(' /api/greengage/user/token?openid=' + openid)
      .then((res) => {
        // debugger;
        if (res.code === 200) {
          const params = res.data
          // params.token='123';
          // const init = JSON.parse(window.localStorage.init)
          localStorage.init = JSON.stringify(params)
          store.commit('setInit', params)
          typeof callback === 'function' && callback(res.data)
          if (params.token) {
            http.defaults.headers.common.Authorization = params.token
          }
          // if (params.first == 1) { // 需要跳转设置regSetting
          // window.location.replace('/regSetting')
          // }
        }
      })
  },
  // 报名后跳转到抽奖页面
  // eslint-disable-next-line camelcase
  goToLottery (lotteryId, fullname, mobile, next, from) {
    goToLink()
    function goToLink () {
      if (lotteryId > 0) {
        if (from === 'form' || from === 'createGroup' || from === 'activityGroup' || from === 'activityGroupDetail' || from === 'activityQues') { // 从报名表单进入的抽奖页面
          router.replace({ path: '/lotteryDetail/' + lotteryId + '?fullname=' + fullname + '&mobile=' + mobile + '+&from=' + from })
        } else {
          router.push({ path: '/lotteryDetail/' + lotteryId + '?fullname=' + fullname + '&mobile=' + mobile + '+&from=' + from })
        }
      } else {
        if (next) {
          next()
        } else {
          router.go(-1)
        }
      }
    }
  }
}
